package com.mgg.user.controller.store;

import com.mgg.common.enums.ResultEnum;
import com.mgg.common.util.BeanUtils;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.user.service.store.StoreService;
import com.mgg.user.vo.UserStoreVO;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("store")
public class StoreController {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private StoreService storeService;
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取附近门店
     * @param storeName
     * @param lng
     * @param lat
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/near")
    public Object getNearbyShop(@RequestHeader(value = "user_id", required = false) String userId,
        @RequestParam(value = "store_name", required = false) String storeName,
        @RequestParam Double lng,
        @RequestParam Double lat,
        @PageableDefault(page = 1, size = 10) Pageable page) {
        List<Map<String,Object>> storeList = storeService.listStore(lng,lat,storeName,page);
        initStoreIsBind(storeList,userId);
        return ResultVOUtil.success(storeList);
    }

    private void initStoreIsBind(List<Map<String,Object>> storeList, String userId) {
        Map<String,Boolean> selectedStoreMap = new HashMap<>();
        if(StringUtils.isNotEmpty(userId)) {
            List<UserStoreVO> userStoreVOList = storeService.listUserStore(userId);
            for (UserStoreVO userStoreVO : userStoreVOList) {
                selectedStoreMap.put(userStoreVO.getStoreCode(),true);
            }
        }
        for (Map<String,Object> store : storeList) {
            String storeCode = store.get("store_code").toString();
            Boolean isBind = false;
            if(selectedStoreMap.containsKey(storeCode)) {
                isBind = selectedStoreMap.get(storeCode);
            }
            store.put("is_bind",isBind);
        }
    }

    /**
     * 门店统计
     * @return
     * @throws Exception
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value = "/count")
    public Object getStoreCount() {
        return ResultVOUtil.success(storeService.countStoreNum());
    }

    /**
     * 搜索门店
     * @param storeName
     * @param page
     * @return
     * @throws Exception
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value = "/search")
    public Object searchStoreList(@RequestHeader(value = "user_id", required = false) String userId, @RequestParam("store_name") String storeName, @PageableDefault(page = 1, size = 10) Pageable page) {
        List<Map<String,Object>> storeList = storeService.listStoreByName(storeName,page);
        initStoreIsBind(storeList,userId);
        return ResultVOUtil.success(storeList);
    }

	/**
	 * 绑定门店
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value = "/bind")
	public Object bindStore(@RequestHeader(value = "user_id") String userId, @RequestParam(value = "store_codes[]") String[] storeCodes) {
	    if (ArrayUtils.isEmpty(storeCodes)) {
            return ResultVOUtil.success();
        }
        for (String storeCode : storeCodes) {
            storeService.insertUserStore(userId, storeCode, false);
        }
		return ResultVOUtil.success();
	}

    /**
     * 解绑门店
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/unbind")
    public Object unbindStore(@RequestHeader(value = "user_id") String userId, @RequestParam(value = "store_codes[]") String[] storeCodes) {
        for (String storeCode : storeCodes) {
            storeService.deleteUserStore(userId,storeCode);
        }
        return ResultVOUtil.success();
    }

    /**
     * 设置当前选择门店
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/select")
    public Object selectStore(@RequestHeader(value = "user_id") String userId, @RequestParam(value = "store_code") String storeCode) {
        UserStoreVO userStoreVO = storeService.getSelectedStore(userId);
        if (userStoreVO != null) {
            if (storeService.updateUserStore(userId, userStoreVO.getStoreCode(), false) == 0) {
                return ResultVOUtil.error(ResultEnum.SYSTEM_ERROR);
            }
        }
        if(storeService.updateUserStore(userId, storeCode, true) == 0) {
            return ResultVOUtil.error(ResultEnum.SYSTEM_ERROR);
        }
        return ResultVOUtil.success();
    }

    /**
     * 绑定门店列表
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/bind/list")
    public Object bindStoreList(@RequestHeader(value = "user_id") String userId) {
       List<UserStoreVO> userStoreVOList = storeService.listUserStore(userId);
        return ResultVOUtil.success(userStoreVOList);
    }
}
